有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在读取文本文件后生成数组

package telephonenumber;

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

public class TelephoneNumber 
{

public static void main(String[] args) 
{
  Scanner k = new Scanner(System.in);
  System.out.println("Enter name of file to read (format: fileName.txt)");
  String fileName = k.nextLine();

  Scanner ipStream = null;
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////   
  try
  {
      ipStream = new Scanner(new File (fileName));

  }
  catch(IOException bad)
  {
              System.out.println("Error opening the file for read:" + fileName);
              System.exit(0);
  }
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////

  while(ipStream.hasNextLine())//file is located
  {
      String dataLine = ipStream.nextLine();
      dataLine.split("  ");
      String zero = line[0];
      String one = line[1];
      String two = line[2];
      String three = line[3];
      String four = line[4];
      System.out.println(line[0]);;

  }



  System.out.println("End of file reached");
  ipStream.close();
}

}

我的文本文件是一系列数字,如下所示:

  • 1551568604
  • 1600771405
  • 774 512 5423
  • 8321056993
  • 7745639912

项目符号不在文本文件中。它只是一行一行地走


如何使每行数字成为一个数组


共 (2) 个答案

  1. # 1 楼答案

    应将返回值split分配给数组:

    String[] line = dataLine.split("  ");
    
  2. # 2 楼答案

    如果你想把每一行添加为元素,你应该看看ArrayList而不是array,因为你不需要担心array的大小。你可以尝试以下方法

    Scanner sc=new Scanner(new File (fileName));
    List<String> list=new ArrayList<>();
    while(sc.hashNextLine()){
      list.add(sc.nextLine());
    }
    

    现在你的List包含所有行。如果我取List中的一个元素,它将是155 156 8604。现在,如果你想按" "分割并得到每个数字,你可以尝试下面的方法

    List<String> numbers=new ArrayList<>();
    for(String i:list){  
       numbers.addAll(Arrays.asList(i.split(" ")));
    }